<template>
  <div class="stu-info-container">
    <!-- 顶部标题栏 -->
    <div class="info-header">
      <h1 class="info-title">个人信息中心</h1>
      <el-button 
        v-if="!isEditMode" 
        type="primary" 
        icon="el-icon-edit" 
        @click="toggleEditMode(true)"
        class="edit-btn"
      >
        编辑个人信息
      </el-button>
    </div>

    <!-- 1. 展示状态：纵向布局（紧凑头像版） -->
    <div v-if="!isEditMode" class="info-display-wrapper">
      <!-- 头像区域：大幅压缩空间 -->
      <div class="avatar-card">
        <img :src="formData.avatar" alt="学生头像" class="compact-avatar">
        <el-button 
          type="text" 
          size="small"  
          @click="handleUploadAvatar"
          class="avatar-upload-btn"
        >
          <i class="el-icon-upload"></i> 更换头像
        </el-button>
      </div>

      <!-- 基本信息卡片：保持清晰 -->
      <div class="info-card">
        <h2 class="card-subtitle">基本信息</h2>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">姓名</span>
            <span class="info-value">{{ formData.name || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">年龄</span>
            <span class="info-value">{{ formData.age || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">性别</span>
            <span class="info-value">{{ formData.sex || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">学号</span>
            <span class="info-value">{{ formData.studentId || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">联系方式</span>
            <span class="info-value">{{ formData.phone || '未填写' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">家长绑定状态</span>
            <span class="info-value">
              <el-tag :type="formData.isBound ? 'success' : 'warning'" size="medium">
                {{ formData.isBound ? '已绑定' : '未绑定' }}
              </el-tag>
              <el-button 
                type="text" 
                size="small" 
                @click="handleBind"
                class="bind-operate-btn"
              >
                {{ formData.isBound ? '查看绑定' : '去绑定' }}
              </el-button>
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 2. 编辑状态：同步紧凑化 -->
    <div v-else class="info-edit-wrapper">
      <div class="edit-header">
        <h2 class="edit-title">编辑个人信息</h2>
        <el-button 
          type="default" 
          icon="el-icon-arrow-left" 
          @click="toggleEditMode(false)"
        >
          取消编辑
        </el-button>
      </div>

      <div class="edit-form-container">
        <!-- 编辑状态头像：同步缩小 -->
        <div class="edit-avatar-section">
          <img :src="formData.avatar" alt="学生头像" class="edit-compact-avatar">
          <el-button 
            type="text" 
            size="small" 
            @click="handleUploadAvatar"
            class="edit-upload-btn"
          >
            <i class="el-icon-upload"></i> 更换头像
          </el-button>
        </div>

        <!-- 表单内容：删除重置按钮，仅保留保存和取消 -->
        <el-form 
          ref="infoForm" 
          :model="formData" 
          label-width="140px" 
          class="info-form"
          :rules="formRules" 
          :disabled="loading"
        >
          <el-form-item label="姓名" prop="name">
            <el-input 
              v-model="formData.name" 
              placeholder="请输入姓名"
              maxlength="10"
              show-word-limit
              size="medium"
            ></el-input>
          </el-form-item>

          <el-form-item label="年龄" prop="age">
            <el-input-number 
              v-model="formData.age" 
              :min="12" 
              :max="20" 
              placeholder="请输入年龄"
              :precision="0"
              size="medium"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-select 
              v-model="formData.sex" 
              placeholder="请选择性别"
              clearable
              size="medium"
            >
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="学号" prop="studentId">
            <el-input 
              v-model="formData.studentId" 
              placeholder="请输入10位学号（如2210240317）"
              maxlength="10"
              show-word-limit
              size="medium"
            ></el-input>
          </el-form-item>

          <el-form-item label="联系方式" prop="phone">
            <el-input 
              v-model="formData.phone" 
              placeholder="请输入手机号"
              maxlength="11"
              show-word-limit
              size="medium"
            ></el-input>
          </el-form-item>

          <el-form-item label="家长绑定状态">
            <div class="bind-status">
              <el-tag :type="formData.isBound ? 'success' : 'warning'" size="small">
                {{ formData.isBound ? '已绑定（家长：请在绑定页面完善信息）' : '未绑定' }}
              </el-tag>
              <el-button 
                type="text" 
                size="small" 
                @click="handleBind"
                class="bind-btn"
              >
                {{ formData.isBound ? '查看绑定' : '去绑定' }}
              </el-button>
            </div>
          </el-form-item>

          <!-- 核心修改：删除“重置表单”按钮，仅保留“保存”和“取消” -->
          <el-form-item>
            <el-button type="primary" @click="handleSave" size="medium">保存信息</el-button>
            <el-button type="default" @click="toggleEditMode(false)" size="medium" style="margin-left: 10px;">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// 脚本逻辑：删除冗余的handleReset方法
import { getStudentInfo, saveStudentInfo, uploadAvatar, getParentBindStatus } from '@/api/student'
import { Message, Loading } from 'element-ui'

export default {
  name: 'StudentInfo',
  data() {
    return {
      formData: {
        name: '',
        age: null,
        sex: '',
        studentId: '',
        phone: '',
        isBound: false,
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      },
      formRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须是整数', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^\d{10}$/, message: '学号必须是10位数字', trigger: 'blur' },
          { minlength: 10, maxlength: 10, message: '学号长度必须为10位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      loading: false,
      loadingInstance: null,
      isEditMode: false,
      originalFormData: {}
    }
  },
  mounted() {
    this.fetchStudentInfo()
  },
  methods: {
    // 从API获取学生信息
    async fetchStudentInfo() {
      try {
        this.loading = true
        this.loadingInstance = Loading.service({ target: '.stu-info-container', text: '加载中...' })
        const response = await getStudentInfo()
        if (response.code === 200) {
          this.formData = { ...this.formData, ...response.data }
          this.originalFormData = { ...this.formData }
        } else {
          Message.error(response.message || '获取信息失败')
        }
      } catch (error) {
        console.error('获取学生信息失败:', error)
        Message.error('获取信息失败，请稍后重试')
      } finally {
        this.loading = false
        this.loadingInstance && this.loadingInstance.close()
      }
    },

    // 保存信息 - 调用API
    async handleSave() {
      this.$refs.infoForm.validate(async (isValid) => {
        if (isValid) {
          try {
            this.loading = true
            const response = await saveStudentInfo(this.formData)
            if (response.code === 200) {
              Message.success('信息保存成功')
              this.originalFormData = { ...this.formData }
              this.toggleEditMode(false)
            } else {
              Message.error(response.message || '保存失败')
            }
          } catch (error) {
            console.error('保存学生信息失败:', error)
            Message.error('保存失败，请稍后重试')
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 家长绑定操作
    async handleBind() {
      if (!this.formData.studentId) {
        Message.warning('请先填写学号')
        return
      }
      try {
        this.loading = true
        const response = await getParentBindStatus(this.formData.studentId)
        if (response.code === 200) {
          this.formData.isBound = response.data.isBound
          this.originalFormData.isBound = response.data.isBound
          if (this.formData.isBound) {
            Message.info('跳转至家长绑定信息页')
          } else {
            Message.info('跳转至家长绑定页')
          }
        }
      } catch (error) {
        console.error('获取绑定状态失败:', error)
        Message.error('操作失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 头像上传 - 调用API
    async handleUploadAvatar() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.onchange = async (e) => {
        const file = e.target.files[0]
        if (!file) return
        try {
          this.loading = true
          const formData = new FormData()
          formData.append('avatar', file)
          const response = await uploadAvatar(formData)
          if (response.code === 200) {
            this.formData.avatar = response.data.avatarUrl
            this.originalFormData.avatar = response.data.avatarUrl
            Message.success('头像上传成功')
          } else {
            Message.error(response.message || '上传失败')
          }
        } catch (error) {
          console.error('上传头像失败:', error)
          Message.error('上传失败，请稍后重试')
        } finally {
          this.loading = false
          input.value = ''
        }
      }
      input.click()
    },

    // 切换编辑/展示状态
    toggleEditMode(flag) {
      this.isEditMode = flag
      if (!flag) {
        // 取消编辑：恢复原始数据（替代原重置按钮功能）
        this.formData = { ...this.originalFormData }
        this.$refs.infoForm && this.$refs.infoForm.resetFields()
      } else {
        // 进入编辑：备份当前数据
        this.originalFormData = { ...this.formData }
      }
    }
  }
}
</script>

<style scoped>
/* 页面容器：保持适中宽度 */
.stu-info-container {
  width: 100%;
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
  font-family: "Microsoft YaHei", sans-serif;
}

/* 顶部标题栏：修复布局冲突（删除标题居中） */
.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeefb;
}
.info-title {
  font-size: 24px; 
  font-weight: bold;
  color: #333;
  margin: 0;
  /* 已删除text-align: center，保持flex左对齐 */
}
.edit-btn {
  font-size: 14px;
  padding: 6px 12px;
}

/* 1. 展示状态：头像区域空间压缩 */
.info-display-wrapper {
  display: grid;
  grid-template-rows: auto 1fr;
  gap: 15px;
}
.avatar-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.compact-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f5f7fa;
  margin-bottom: 8px;
}
.avatar-upload-btn {
  font-size: 12px;
  color: #409EFF;
  padding: 0;
}

/* 基本信息卡片 */
.info-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 25px;
}
.card-subtitle {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-top: 0;
  margin-bottom: 18px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
  text-align: center;
}
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}
.info-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}
.info-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 6px;
}
.info-value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}
.bind-operate-btn {
  margin-left: 8px;
  font-size: 14px;
  padding: 0;
  color: #409EFF;
}

/* 2. 编辑状态 */
.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.edit-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.edit-form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 25px;
}
.edit-avatar-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}
.edit-compact-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}
.edit-upload-btn {
  color: #409EFF;
  font-size: 12px;
}

/* 表单样式 */
.info-form {
  padding: 0;
  box-shadow: none;
  background: transparent;
}
.el-form-item {
  margin-bottom: 18px;
}
.el-input--medium, .el-select--medium, .el-input-number--medium {
  font-size: 14px;
  height: 40px;
}
.el-form-item__label {
  font-size: 14px;
  color: #606266;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  .compact-avatar {
    width: 60px;
    height: 60px;
  }
}
</style>